<template>
  <!-- <a-table :columns="columns" :scroll="{ y: 400 }" :pagination="false" :data-source="dataSource" :animate-rows="false" /> -->
  <div class="p-4 quan">
    <a-row :gutter="16" style="height: 100%">
      <a-col class="gutter-row equipment p-4" :span="7">
        <div class="gutter-box">
          <div class="equipment_tit dis_sb">
            <div class="dis_row">
              <div class="equipment_zs">
                <div class="equipment_zs_s"></div>
              </div>
              <span>{{ userName }}-设备列表</span>
            </div>
            <a-select v-model:value="chooseOp" label-in-value style="width: 120px" :options="options"
              @change="handleChange" />
          </div>
          <div class="equipment_list p-3 y_scroll">
            <div v-if="equipment_list.length === 0">无站点</div>
            <div v-else class="equipment_list_item dis_row" v-for="(item, index) in equipment_list" :key="index">
              <img class="equipment_list_icon" src="@/assets/images/equipment.png" alt="" />
              <div class="equipment_list_xx">
                <div class="dis_sb equipment_zdxx">
                  <div style="width: 75%">{{ item.name }}</div>
                  <div class="equipment_zdxx_more" @click="setDeviceData(item)">查看 >></div>
                </div>
                <div class="equipment_zdwz">
                  <div class="site_status">
                    <div class="site_status_zs"></div>在线
                  </div>
                  <!-- <div class="site_status site_status1"><div class="site_status_zs"></div>不在线</div> -->
                  <div class="equipment_zdwz_l">站点位置：{{ item.zdwz }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-col>
      <a-col class="gutter-row" :span="17">
        <div class="gutter-box site p-4">
          <div class="equipment_tit dis_row">
            <div class="equipment_zs">
              <div class="equipment_zs_s"></div>
            </div>
            <span>站点数据-{{ dataTime }}</span>
          </div>
          <div class="y_scroll">
            <div v-if="site_list.length === 0" style="text-align: center"><img class="site_wudata"
                src="@/assets/images/wudata.png" alt="" /></div>
            <a-row v-else :gutter="{ xs: 8, sm: 8, md: 12 }">
              <a-col class="gutter-row" :span="8" v-for="(item, index) in site_list" :key="index">
                <div class="gutter-box site_item">
                  <div class="site_item_zs"></div>
                  <div class="site_item_clear p-4">
                    <div class="dis_row site_item_sitexx">
                      <img class="site_item_img" :src="item.icon" alt="" />
                      <div class="">
                        <div class="site_item_sitesz">{{ item.value }} {{ item.unit }}</div>
                        <div class="site_item_sitetit">{{ item.name }}</div>
                      </div>
                    </div>
                    <div class="site_history dis_row" @click="handleAdd(item.key)">
                      <!-- <img class="site_history_icon" src="/history.png" alt="" /> -->
                      <svg class="site_history_icon" xmlns="http://www.w3.org/2000/svg"
                        xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20" viewBox="0 0 20 20"
                        fill="none">
                        <g opacity="1" transform="translate(0 0)  rotate(0)">
                          <mask id="bg-mask-0" fill="white">
                            <use transform="translate(0 0)  rotate(0)" xlink:href="#path_0" />
                          </mask>
                          <g mask="url(#bg-mask-0)">
                            <path id="路径 1" fill-rule="evenodd" style="fill: #000000" opacity="0.4"
                              d="M5.37125 4.3175C5.75125 4.3175 6.03125 4.0275 6.03125 3.6875L6.03125 1.0975C6.03125 0.7175 5.75125 0.4375 5.37125 0.4375L4.94125 0.4375C4.56125 0.4375 4.28125 0.7175 4.28125 1.0975L4.28125 3.6875C4.28125 4.0275 4.56125 4.3175 4.94125 4.3175L5.37125 4.3175Z" />
                            <path id="路径 2" fill-rule="evenodd" style="fill: #000000" opacity="0.4"
                              d="M17.8438,2.59375c0.75,0 1.3099,0.59 1.3099,1.31v14.34995c-0.0299,0.75 -0.59,1.31 -1.34,1.31h-15.65995c-0.75,0 -1.31,-0.56 -1.31,-1.31v-14.34995c0,-0.75 0.56,-1.31 1.31,-1.31h1.28v1.09c0,0.88 0.72,1.54 1.53,1.54h0.44c0.88,0 1.53,-0.72 1.53,-1.54v-1.09h6.09995v1.09c0,0.88 0.72,1.54 1.5301,1.54h0.4399c0.87,0 1.53,-0.72 1.53,-1.54v-1.09zM17.8438,18.2537c-0.0301,0 -0.0301,-11.31995 -0.0301,-11.31995h-15.65995v11.31995z" />
                            <path id="路径 3" fill-rule="evenodd" style="fill: #000000" opacity="0.4"
                              d="M14.53,4.3075c-0.37,0 -0.65,-0.28 -0.65,-0.62v-2.59c0,-0.38 0.28,-0.66 0.65,-0.66h0.44c0.37,0 0.66,0.28 0.66,0.66v2.59c0,0.34 -0.29,0.62 -0.66,0.62zM9.5,9.6575h0.97v2.87l1.34,1.44l-0.72,0.66l-1.59,-1.75z" />
                            <path id="路径 4" fill-rule="evenodd" style="fill: #000000" opacity="0.4"
                              d="M12.6262 8.52711C11.4662 7.84711 10.1562 7.62711 8.93624 7.90711C8.18624 8.06711 7.46624 8.43711 6.87625 8.93711C6.59625 9.18711 6.34625 9.4371 6.12625 9.7171L6.12625 9.2171L5.15625 9.2171L5.15625 11.7171L7.68624 11.7171L7.68624 10.7771L6.59625 10.7771C7.12624 9.8171 8.03624 9.09711 9.12624 8.84711C10.1562 8.59711 11.1862 8.81711 12.0662 9.34711C12.9662 9.8771 13.5962 10.7471 13.7862 11.7171C13.9962 12.6871 13.8762 13.7171 13.2862 14.6271C12.7462 15.4971 11.8762 16.0971 10.8762 16.3471C9.84624 16.5971 8.81624 16.3771 7.93624 15.8471C7.03624 15.3171 6.40625 14.4371 6.21625 13.4671L5.28625 13.6271C5.56625 14.8471 6.34625 15.9071 7.43624 16.6271C8.21624 17.1271 9.12624 17.3771 10.0362 17.3771C10.4062 17.3771 10.7862 17.3471 11.1262 17.2471C12.4062 16.9671 13.4662 16.1871 14.1562 15.1271C14.8462 14.0671 15.0662 12.7771 14.7862 11.5271C14.4962 10.3171 13.7162 9.24711 12.6262 8.52711Z" />
                          </g>
                        </g>
                        <defs>
                          <rect id="path_0" x="0" y="0" width="20" height="20" />
                        </defs>
                      </svg>
                      历史记录
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
        </div>
      </a-col>
    </a-row>
    <ThingsDataModal @register="registerModal1"></ThingsDataModal>
    <ThingsUserModal @register="registerModal2" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defHttp } from '@/utils/http/axios';
import { useModal } from '/@/components/Modal';
import ThingsDataModal from './components/ThingsDataModal.vue';
import ThingsUserModal from './components/ThingsUserModal.vue';
import dayjs from 'dayjs';

interface Value {
  value?: string;
  label?: string;
}
//注册model
const [registerModal1, { openModal }] = useModal();
const [registerModal2, { openModal: openModal2 }] = useModal();
const site_list = ref([
  // {
  //   icon: '',
  //   zxsj: '24.0',
  //   sjdw: '°C',
  //   name: '土壤温度',
  //   status: true,
  //   lsjl: '',
  // },
]);
const equipment_list = ref([]);

const userName = ref('');
const {
  query: { id: id, name: name },
} = useRoute();
userName.value = name;
console.log(id);
// 字段
const columns = ref([]);
// 数据
const data = ref([]);
// 数据时间
const dataTime = ref(null);
const options = ref([
  {
    value: 'atmosphere',
    label: '气象监测',
  },
  {
    value: 'soil',
    label: '土壤监测',
  },
  {
    value: 'water',
    label: '水质监测',
  },
  {
    value: 'insectPest',
    label: '虫害监测',
  },
]);
// 选项
const chooseOp = ref<Value>({ value: 'atmosphere' });
const handleChange = (value: Value) => {
  // 设置显示
  setShowDeviceData(value.value);
};
// 总的设备数据,equipment_list:为当前页面需要现实的数据
let totalDeviceData = ref([]);

let fieldMap = ref({});
// 设备数据
function device(page) {
  defHttp.get({ url: '/thingsUserDevice/list', params: Object.assign(page, { id: id }) }).then((res) => {
    console.log(res);
    totalDeviceData.value = res.data;
    // 设置默认显示的是大气数据
    setShowDeviceData('atmosphere');
  }).catch(err => {
    openModal2(true, {
      isUpdate: false,
      showFooter: true,
    });
  });
}
// 设置页面需要显示的数据,根据type类型进行过滤
function setShowDeviceData(type) {
  let showData = [];
  for (let i = 0; i < totalDeviceData.value.length; i++) {
    if (totalDeviceData.value[i].label === type) {
      showData.push(totalDeviceData.value[i]);
    }
  }
  equipment_list.value = showData;
  if (equipment_list.value.length > 0) {
    setDeviceData(equipment_list.value[0]);
  } else {
    setDeviceData(null);
  }
}
// ws当前连接设备id
const currentDeviceId = ref();
// 设置设备最新数据
function setDeviceData(deviceData) {
  if (!deviceData || !deviceData.deviceLatestData) {
    site_list.value = [];
    return;
  }

  let deviceLatestData = deviceData.deviceLatestData;
  // 设置数据时间
  dataTime.value = dayjs(deviceLatestData[0].ts).format('YYYY-MM-DD HH:mm:ss');

  // 获取映射数据
  if (deviceData.attributeInfo) {
    deviceData.attributeInfo.forEach((item) => {
      if (item.key === 'attributeInfo' && item.value) {
        fieldMap = JSON.parse(item.value);
      }
    });
  }

  // 排序
  deviceLatestData = sortArray(deviceLatestData);
  // 设置右侧数据
  const data = [];
  deviceLatestData.forEach((item) => {
    if (item.key in fieldMap) {
      data.push({
        key: item.key,
        name: fieldMap[item.key].name,
        unit: fieldMap[item.key].unit,
        icon: fieldMap[item.key].icon,
        value: item.value,
      });
    }
  });

  // 赋值
  site_list.value = data;
  if (currentDeviceId.value !== deviceData.id.id) {
    // 连接ws，接收数据
    WebSocketConnect(deviceData.id.id);
  }
}
// 发起数据访问
onMounted(() => {
  // 当页面加载完成后执行这里的代码
  device({ pageSize: 100, pageNo: 1 });
});
// ws 连接
function WebSocketConnect(deviceId) {
  defHttp.get({ url: '/thingsUserDevice/getUserToken/', params: { id: id } }).then((res) => {
    let webSocket = new WebSocket('wss://agri.cng-zh.com:28080/api/ws/plugins/telemetry?token=' + res);
    // 开启监听
    webSocket.onopen = function () {
      var object = {
        tsSubCmds: [
          {
            entityType: 'DEVICE',
            entityId: deviceId,
            scope: 'LATEST_TELEMETRY',
            cmdId: 11,
          },
        ],
        historyCmds: [],
        attrSubCmds: [],
      };
      var data = JSON.stringify(object);
      webSocket.send(data);
    };
    // 修改当前ws的连接设备
    currentDeviceId.value = deviceId;
    // 监听数据
    webSocket.onmessage = (event) => {
      var received_msg = event.data;
      let jsonData = JSON.parse(received_msg);
      for (var i = 0; i < equipment_list.value.length; i++) {
        if (equipment_list.value[i].id.id === deviceId) {
          let data = [];
          Object.entries(jsonData.data).forEach(([key, value]) => {
            data.push({ ts: value[0][0], key: key, value: value[0][1] });
          });
          // 排序并赋值
          equipment_list.value[i].deviceLatestData = sortArray(data);
          // 更新视图数据
          setDeviceData(equipment_list.value[i]);
          break;
        }
      }
    };
  });
}

// 排序数组
function sortArray(arr) {
  arr.sort((a, b) => {
    if (a.key < b.key) {
      return -1;
    }
    if (a.key > b.key) {
      return 1;
    }
    return 0;
  });
  return arr;
}
/**
 * 历史数据事件
 */
function handleAdd(key) {
  openModal(true, {
    data: {
      id: id, deviceId: currentDeviceId.value, key: key,
      fieldMap: fieldMap
    },
    isUpdate: false,
    showFooter: true,
  });
}
</script>
<style lang="less">
.y_scroll {
  overflow: hidden;
  overflow-y: scroll;
  height: calc(100vh - 210px);
  // border: 1px solid red;
}

.y_scroll::-webkit-scrollbar {
  width: 0 !important;
}

.quan {
  height: calc(100vh - 110px);
  overflow: hidden;
  overflow-y: scroll;
}

.site {
  background: #fff;
  height: 100%;
  position: relative;

  &_wudata {
    width: 40%;
    opacity: 0.5;
  }

  &_history {
    width: 100%;
    padding: 10px 0px 0px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    font-size: 0.87rem;
    cursor: pointer;
    color: rgba(0, 0, 0, 0.4);
    font-size: 0.75rem;

    &_icon {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }

  &_history:hover {
    color: #00873c;
    opacity: 0.8;
  }

  &_history:hover &_history_icon path {
    fill: #00873c !important;
    opacity: 1;
  }

  &_item {
    position: relative;
    border-radius: 15px;
    overflow: hidden;
    transition: all 0.5s;
    margin-bottom: 20px;
    background: transparent;
    box-shadow: 1px 2px 10px rgba(115, 115, 115, 0.2);

    &_zs {
      background: #68e2e5;
      position: absolute;
      left: 0;
      top: 10px;
      bottom: 10px;
      width: 2px;
      border-radius: 1px;
    }

    &_sitesz {
      // color: rgba(0, 0, 0, .4);
      font-size: 1.1rem;
      font-weight: 500;
    }

    &_sitetit {
      color: rgba(0, 0, 0, 0.4);
      font-size: 0.75rem;
    }

    &_sitexx {
      padding-bottom: 20px;
    }

    &_img {
      width: 50px;
      height: 50px;
      background: #2ec7c9;
      margin-right: 15px;
      border-radius: 10px;
    }

    &:hover {
      box-shadow: 2px 2px 10px rgba(28, 162, 226, 0.25);
      // transform: scale(1.01);
      transform-origin: center center;
      backface-visibility: hidden;
    }

    &_clear {
      // position: absolute;
      // top: 0;
      // left: 0;
      // right: 0;
      // bottom: 0;
    }
  }
}

.site_status {
  width: 20%;
  color: #4ec992;
  // padding: 4px 15px;
  border-radius: 0px 10px 0px 10px;
  // font-size: 12px;
  display: flex;
  flex-direction: row;
  align-items: center;

  .site_status_zs {
    width: 6px;
    height: 6px;
    background: #4ec992;
    border-radius: 50%;
    margin-right: 10px;
  }
}

.site_status1 {
  color: #d1d1d1;

  .site_status_zs {
    background: #d1d1d1;
  }
}

.equipment {
  background: #fff;
  height: 100%;

  &_zdwz {
    font-size: 13px;
    color: rgba(0, 0, 0, 0.5);
    margin-left: 10px;
    margin-top: 6px;
    display: flex;
    flex-direction: row;
    align-items: center;

    &_l {
      max-width: 70%;
    }
  }

  &_zdxx {
    padding: 4px 10px;
    background: linear-gradient(90deg, rgba(28, 162, 226, 0) 0%, rgba(28, 162, 226, 0.1) 47.22%, rgba(28, 162, 226, 0) 100%);

    &_more {
      font-size: 12px;
      color: rgba(0, 193, 251, 1);
      cursor: pointer;
    }
  }

  &_list {
    background: rgba(0, 193, 251, 0.05);
    // border: 1px solid rgba(28, 162, 226, 0.2);
    padding-bottom: 20px;

    &_item {
      margin-bottom: 30px;

      &:last-child {
        margin-bottom: 0px;
      }
    }

    &_xx {
      width: 80%;
    }

    &_icon {
      width: 50px;
      height: 50px;
      // background: rgba(28, 162, 226, .5);
      margin-right: 5%;
    }
  }

  &_tit {
    margin-bottom: 15px;
  }

  &_zs {
    width: 16px;
    height: 16px;
    padding: 4px;
    border: 1px solid rgba(24, 144, 255, 0.5);
    position: relative;
    margin-right: 8px;

    &_s {
      width: 8px;
      height: 8px;
      padding: 4px;
      background: rgba(24, 144, 255, 0.5);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}

.dis_sb {
  display: flex;
  justify-content: space-between;
}

.dis_row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.ml_90 {
  margin-left: 90px;
}

.graph {
  width: 100%;
  margin: 0px;
  background: #fff;
}

html[data-theme='dark'] .equipment,
html[data-theme='dark'] .site {
  background: #151515 !important;
}

html[data-theme='dark'] .equipment_zdwz,
html[data-theme='dark'] .site_item_sitetit,
html[data-theme='dark'] .site_history {
  color: rgba(255, 255, 255, 0.4);
}

html[data-theme='dark'] .site_history_icon path {
  fill: rgb(255, 255, 255) !important;
}

html[data-theme='dark'] .site_history {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

html[data-theme='dark'] .site_wudata {
  opacity: 0.4 !important;
}

html[data-theme='dark'] .equipment_list {
  background: rgba(0, 193, 251, 0.01);
}
</style>
